<template>
  <div>
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>
        <a href="/">用户管理</a>
      </el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card class="box-card">
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input placeholder="请输入内容" v-model="queryInfo.query" clearable @clear="getUserList">
            <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="addUser">添加用户</el-button>
        </el-col>
      </el-row>
    </el-card>
    <el-table :data="userList" stripe style="width: 100%" border>
      <el-table-column type="index" label="序号" width="60" align="center"></el-table-column>
      <el-table-column prop="username" label="姓名" width="150" align="center"></el-table-column>
      <el-table-column prop="role_name" label="角色名称" width="180" align="center"></el-table-column>
      <el-table-column prop="mobile" label="手机号码" width="180" align="center"></el-table-column>
      <el-table-column prop="email" label="邮箱" width="180" align="center"></el-table-column>
      <el-table-column prop="mg_state" label="状态" width="100" align="center">
        <template slot-scope="scope">
          <el-switch v-model="scope.row.mg_state" @change="statusChange(scope.row)" />
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center">
        <template slot-scope="scope">
          <el-tooltip class="item" effect="dark" content="编辑" placement="top" :enterable="false">
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="editUser(scope.row.id)"
            ></el-button>
          </el-tooltip>
          <el-tooltip class="item" effect="dark" content="删除" placement="top" :enterable="false">
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="delUser(scope.row.id)"
            ></el-button>
          </el-tooltip>
          <el-tooltip effect="dark" content="角色分配" placement="top" :enterable="false">
            <el-button
              type="warning"
              icon="el-icon-setting"
              size="mini"
              @click="editRoleUser(scope.row)"
            ></el-button>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="queryInfo.pagenum"
      :page-sizes="[1, 2, 5, 10]"
      :page-size="queryInfo.pagesize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
    ></el-pagination>

    <el-dialog :title="titleDia" :visible.sync="adddialogVisible" width="50%" @close="closedialog">
      <!-- 内容主题 -->
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="70px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password" v-if="passwordFlag">
          <el-input v-model="addForm.password" type="password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="addForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="adddialogVisible = false">取 消</el-button>
        <!--<el-button type="primary" @click="adddialogVisible = false">确 定</el-button>-->
        <el-button type="primary" @click="saveInfoUser">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog title="分配角色" :visible.sync="dialogVisible" width="50%">
      <div>
        <p>当前用户：{{userInfo.username}}</p>
        <p>当前角色：{{userInfo.role_name}}</p>
        <p>选择角色:
          <el-select v-model="value" placeholder="请选择">
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </p>
      </div>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data () {
    var checkEmail = (rule, value, callback) => {
      const regEmail = /^\w+@\w+(\.\w+)+$/;
      if (regEmail.test(value)) {
        // 合法邮箱
        return callback();
      }
      callback(new Error("请输入合法邮箱"));
    };
    // 自定义手机号规则
    var checkMobile = (rule, value, callback) => {
      const regMobile = /^1[34578]\d{9}$/;
      if (regMobile.test(value)) {
        return callback();
      }
      // 返回一个错误提示
      callback(new Error("请输入合法的手机号码"));
    };
    return {
      queryInfo: {
        query: "",
        // 当前页数
        pagenum: 1,
        pagesize: 5,
      },
      userList: [],
      total: 0,
      passwordFlag: true,
      // 控制对话框
      adddialogVisible: false,
      addForm: {},
      titleDia: '',
      userInfo: {},
      addFormRules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          {
            min: 2,
            max: 10,
            message: "用户名的长度在2～10个字",
            trigger: "blur",
          },
        ],
        password: [
          { required: true, message: "请输入用户密码", trigger: "blur" },
          {
            min: 6,
            max: 18,
            message: "用户密码的长度在6～18个字",
            trigger: "blur",
          },
        ],
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          { validator: checkEmail, trigger: "blur" },
        ],
        mobile: [
          { required: true, message: "请输入手机号码", trigger: "blur" },
          { validator: checkMobile, trigger: "blur" },
        ],
      },
    };
  },
  methods: {
    async editRoleUser (role) {

    },
    async delUser (id) {
      // const { data: res } = await this.$http.delete('users/' + id)
      const confirmResult = await this.$confirm("确定删除此用户", '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      // 点击确定 返回值为：confirm
      // 点击取消 返回值为： cancel
      if (confirmResult !== 'confirm') {
        return this.$message.info('已取消删除')
      }
      const { data: res } = await this.$http.delete('users/' + id)
      if (res.meta.status !== 200) return this.$message.error('删除用户失败！')
      this.$message.success('删除用户成功！')
      this.getUserList()
    },
    addUser () {
      this.titleDia = "新增用户"
      this.adddialogVisible = true
    },
    closedialog () {
      this.addForm = {}
      this.passwordFlag = true
    },
    async editUser (id) {
      // this.$nextTick(() => {
      //   //DOM现在更新了
      //   console.log(this.$refs);
      // });
      const { data: res } = await this.$http.get(`users/${id}`);
      this.addForm = res.data;
      this.adddialogVisible = true;
      this.passwordFlag = false;
      this.titleDia = "修改用户"
      //this.addFormRules.password[0].required = false;
    },
    async editInfoUser () {
      this.$refs.addFormRef.validate(async (valid) => {
        if (!valid) return;
        const { data: res } = await this.$http.put(`users/${this.addForm.id}`, {
          email: this.addForm.email,
          mobile: this.addForm.mobile
        });
        console.log(res)
        if (res.meta.status !== 201) {
          this.$message.error("修改用户失败：" + res.meta.msg);
        }
        this.$message.success("修改用户成功");
      });
    },
    async saveInfoUser () {
      if (this.titleDia === '修改用户')
        this.editInfoUser()
      if (this.titleDia === '添加用户') {
        this.passwordFlag = true;
        this.$refs.addFormRef.validate(async (valid) => {
          if (!valid) return;
          const { data: res } = await this.$http.post("users", this.addForm);
          if (res.meta.status !== 201) {
            this.$message.error("添加用户失败：" + res.mate.message);
          }
          this.$message.success("添加用户成功");
        })
      }
      this.$refs.addFormRef.clearValidate()
      this.adddialogVisible = false;
      this.getUserList();
    },
    // 状态改变
    async statusChange (rows) {
      const { data: res } = await this.$http.put(
        `users/${rows.id}/state/${rows.mg_state}`
      );
      console.log(res);
      if (res.meta.status !== 200) {
        // 取反 把之前的值设置回去
        rows.mg_state = !rows.mg_state;
        return this.$message.error("更新用户状态失败:" + res.meta.msg);
      }
      this.$message.success("更新用户状态成功！");
    },
    // 更改分页
    handleSizeChange (newSize) {
      this.queryInfo.pagesize = newSize;
      this.getUserList();
    },
    handleCurrentChange (newPage) {
      this.queryInfo.pagenum = newPage;
      this.getUserList();
    },
    //获取用户列表
    async getUserList () {
      const { data: rest } = await this.$http.get("users", {
        params: this.queryInfo,
      });
      console.log(rest);
      if (rest.meta.status !== 200)
        return this.$message.error("获取用户列表失败");
      this.userList = rest.data.users;
      this.total = rest.data.total;
    },
  },
  created () {
    this.getUserList();
  },
};
</script>
<style lang="less" scoped>
.el-pagination {
  margin-top: 15px;
}
</style>
